﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Logistics_Service.DTO;

namespace Logistics_Service.DAO
{
    public class ChiNhanhDAO
    {
        public ChiNhanhDTO[] DanhSachChiNhanh()
        {
            ChiNhanhDTO[] arr;
            string query = string.Format("select * from ChiNhanh");
            DataProvider provider = new DataProvider();
            DataTable dt = provider.ExecuteQuery(query);
            int n = dt.Rows.Count;
            arr = new ChiNhanhDTO[n];
            for (int i = 0; i < n; i++)
            {
                object td = GetDataFromDataRow(dt, i);
                arr[i] = (ChiNhanhDTO)td;
            }
            return arr;
        }
        protected object GetDataFromDataRow(DataTable dt, int i)
        {
            ChiNhanhDTO cn = new ChiNhanhDTO();
            cn.Ma = dt.Rows[i]["Ma"].ToString();
            cn.Ten = dt.Rows[i]["Ten"].ToString();
            cn.DiaChi = dt.Rows[i]["DiaChi"].ToString();
            cn.SDT = dt.Rows[i]["SDT"].ToString();

            cn.TinhThanh = TinhThanhDAO.Get(dt.Rows[i]["MaTinhThanh"].ToString());
           
            return (object)cn;
        } 

        public static ChiNhanhDTO Get(string ma)
        {
            ChiNhanhDTO cn = new ChiNhanhDTO();
            string query = "select * from ChiNhanh where Ma = '" + ma + "'";
            DataProvider provider = new DataProvider();
            DataTable dt = provider.ExecuteQuery(query);

            cn.Ma = ma;
            cn.Ten = dt.Rows[0]["Ten"].ToString();
            cn.DaXoa = bool.Parse(dt.Rows[0]["DaXoa"].ToString());
            cn.DiaChi = dt.Rows[0]["DiaChi"].ToString();
            cn.SDT = dt.Rows[0]["SDT"].ToString();
            cn.TinhThanh = TinhThanhDAO.Get(dt.Rows[0]["MaTinhThanh"].ToString());

            return cn;
        }

        public bool ThemChiNhanh(string ten, string diachi, string sdt, string matinhthanh)
        {
            string query = "insert into chinhanh (Ma, Ten, DiaChi, SDT, MaTinhThanh) values(N'1',N'" + ten + "',N'" + diachi + "','" + sdt + "','" + matinhthanh + "')";
            DataProvider dp = new DataProvider();
            bool kq = dp.ExecuteNonQuery(query);
            return kq;
        }
    }
}